package com.guangyuan.network.test;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.guangyuan.network.datasource.pool.util.ConnectionUtil;

public class CreateSql {
	private static Map<String, TableMeta> tables = new HashMap<String, TableMeta>();

	private static void getHeader(String tableName) {
		Connection conn = ConnectionUtil.getConnection();

		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery("desc " + tableName);

			List<String> headers = new ArrayList<String>();
			StringBuilder select = new StringBuilder();
			StringBuilder update = new StringBuilder();

			while (rs.next()) {
				headers.add(rs.getString(1));
				select.append(rs.getString(1) + ",");
				update.append(rs.getString(1) + "=?,");
			}
			select.delete(select.lastIndexOf(","), select.length());
			update.delete(update.lastIndexOf(","), update.length());

			tables.put(tableName, new TableMeta("select " + select.toString() + " from " + tableName , "update " + tableName + " set " + update
					.toString() + " where " + headers.get(0) + " = ?", headers));
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			ConnectionUtil.closeConnection(conn);
		}
	}

	public static TableMeta getTableMeta(String tableName) {
		TableMeta tableMeta = tables.get(tableName);
		if(null == tableMeta) {
			getHeader(tableName);
			tableMeta = tables.get(tableName);
		}
		return tableMeta;
	}

	public static void main(String[] args) {
		CreateSql sql = new CreateSql();
		TableMeta tableMeta = sql.getTableMeta("product_group");
		System.out.println(tableMeta.getSelectSql());
		System.out.println(tableMeta.getUpdateSql());
	}
}
